package org.JWCB.system.service.user.impl;


import com.github.pagehelper.PageHelper;
import org.JWCB.system.domain.user.dto.UserQueryDto;
import org.JWCB.system.domain.user.entity.User;
import org.JWCB.system.domain.user.vo.UserListItemVo;
import org.JWCB.common.core.enums.ResultCode;
import org.JWCB.common.core.enums.UserStatus;
import org.JWCB.common.core.exception.ServiceException;
import org.JWCB.system.manager.UserCacheManager;
import org.JWCB.system.mapper.user.UserMapper;
import org.JWCB.system.service.user.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserService implements IUserService {
    @Autowired
    private UserMapper userMapper;


    @Autowired
    private UserCacheManager userCacheManager;

    @Override
    public List<UserListItemVo> list(UserQueryDto userQueryDto) {
        PageHelper.startPage(userQueryDto.getPageNum(),userQueryDto.getPageSize());
        return userMapper.selectUserList(userQueryDto);
    }

    @Override
    public int blacklist(Long userId) {
        User user = getUserById(userId);
        user.setStatus(UserStatus.BLACKED.getCode());
        userCacheManager.updateUserStatus(userId,UserStatus.BLACKED.getCode());
        return userMapper.updateById(user);
    }


    @Override
    public int liftBan(Long userId) {
        User user = getUserById(userId);
        user.setStatus(UserStatus.NORMAL.getCode());
        userCacheManager.updateUserStatus(userId,UserStatus.NORMAL.getCode());
        return userMapper.updateById(user);
    }

    /**
     * 通过id获取用户
     * @return
     */
    private User getUserById(Long userId) {
        User user = userMapper.selectById(userId);
        if(user == null) {
            throw new ServiceException(ResultCode.FAILED_NOT_EXISTS);
        }
        return user;
    }

}
